import pymysql

"""
create table if not exists users (
    id bigint UNSIGNED AUTO_INCREMENT,
    username varchar(20),
    password varchar(32),
    PRIMARY KEY (id) 
);
"""

connect = pymysql.connect(host="master", port=3306, user="root", passwd="123456", db="bigdata")


# 注册
def register():
    username = input("请输入用户名：")
    password = input("请输入密码：")
    new_password = input("请确认密码：")

    # 判断两次密码是否一致
    if password != new_password:
        print("两次密码输入不一致")
        register()
    else:
        # 判断用户名是否存在
        cursor = connect.cursor()
        cursor.execute(f"select * from users where username=%s", [username])
        # 获取查询结果
        query_user = cursor.fetchone()
        if query_user is not None:
            print("用户名已存在")
            register()
        else:
            # 将用户名密码保存到数据库
            execute = cursor.execute(f"insert into users(username,password) values(%s,md5(%s))", [username, password])
            if execute == 1:
                print("注册成功！")
                # 提交事务
                connect.commit()


# 登录
def login():
    username = input("请输入用户名：")
    password = input("请输入密码：")

    # 判断用户名是否存在
    cursor = connect.cursor()
    # ' or '1'='1:sql注入
    # 处理方式：采用预编译sql语句
    cursor.execute("select * from users where username=%s", [username])
    query_user = cursor.fetchone()
    print(query_user)
    if query_user is None:
        print("用户名不存在！")
        login()
    else:
        # 判断密码是否一致
        cursor.execute(f"select * from users where username=%s and password=md5(%s)", [username, password])
        query_user = cursor.fetchone()
        print(query_user)
        if query_user is None:
            print("密码不对")
            login()
        else:
            print("登录成功")


# 修改密码
def modify_password():
    username = input("请输入用户名:")
    old_password = input("请输入原密码:")
    new_password = input("请输入新密码:")

    cursor = connect.cursor()
    # 验证用户名和密码是否正确
    cursor.execute("select * from users where username=%s and password=md5(%s)", [username, old_password])
    user = cursor.fetchone()
    if user is None:
        print("用户名密码不正确")
        modify_password()
    else:
        cursor.execute(f"update users set password=md5(%s) where username=%s", [new_password, username])
        connect.commit()
        print("密码修改成功")


if __name__ == '__main__':
    while True:
        print("请选择，1：登录，2：注册，3：修改密码")
        i = input("请选择")
        if i == "1":
            login()
        elif i == "2":
            register()
        elif i == "3":
            modify_password()
        else:
            print("退出系统")
            break
